package com.bjsxt.tank;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 登录窗口（含用户手册）
 */
public class LoginFrame extends JFrame {
    // 常量定义
    private static final Color BG_COLOR = new Color(45, 45, 45);
    private static final Color TEXT_COLOR = new Color(200, 200, 200);
    private static final Font LABEL_FONT = new Font("微软雅黑", Font.BOLD, 14);

    private JTextField usernameField = new JTextField(15);
    private JPasswordField passwordField = new JPasswordField(15);

    public LoginFrame() {
        initUI();
        setLocationRelativeTo(null);
    }

    private void initUI() {
        setTitle("坦克大战登录 v2.0");
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        // 主容器使用分层面板
        JLayeredPane layeredPane = new JLayeredPane();
        layeredPane.setPreferredSize(new Dimension(400, 300));

        // 背景面板
        JPanel bgPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setPaint(new GradientPaint(0, 0, Color.DARK_GRAY, 400, 300, Color.BLACK));
                g2d.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        bgPanel.setBounds(0, 0, 400, 300);

        // 主内容面板
        JPanel mainPanel = createMainPanel();
        mainPanel.setBounds(50, 40, 300, 200);

        // 帮助按钮
        JButton helpBtn = createHelpButton();
        helpBtn.setBounds(320, 10, 70, 25);

        layeredPane.add(bgPanel, JLayeredPane.DEFAULT_LAYER);
        layeredPane.add(mainPanel, JLayeredPane.PALETTE_LAYER);
        layeredPane.add(helpBtn, JLayeredPane.PALETTE_LAYER);

        add(layeredPane);
    }

    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new GridLayout(4, 1, 10, 10));
        panel.setOpaque(false);

        // 标题
        JLabel title = new JLabel("坦克大战登录系统", SwingConstants.CENTER);
        title.setFont(new Font("微软雅黑", Font.BOLD, 18));
        title.setForeground(new Color(0, 150, 255));
        panel.add(title);

        // 输入组件
        panel.add(createInputPanel("用户名:", usernameField));
        panel.add(createInputPanel("密码:", passwordField));

        // 按钮面板
        JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
        btnPanel.setOpaque(false);

        JButton loginBtn = createStyledButton("登录", new Color(0, 150, 255));
        loginBtn.addActionListener(new LoginHandler());
        btnPanel.add(loginBtn);

        JButton cancelBtn = createStyledButton("取消", new Color(200, 50, 50));
        cancelBtn.addActionListener(e -> System.exit(0));
        btnPanel.add(cancelBtn);

        panel.add(btnPanel);
        return panel;
    }

    private JPanel createInputPanel(String label, JComponent field) {
        JPanel panel = new JPanel(new BorderLayout(10, 0));
        panel.setOpaque(false);

        JLabel lbl = new JLabel(label);
        lbl.setFont(LABEL_FONT);
        lbl.setForeground(TEXT_COLOR);
        panel.add(lbl, BorderLayout.WEST);

        field.setFont(LABEL_FONT);
        field.setBackground(BG_COLOR);
        field.setForeground(Color.WHITE);
        field.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(100, 100, 100)),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
        ));
        panel.add(field, BorderLayout.CENTER);

        return panel;
    }

    private JButton createStyledButton(String text, Color bgColor) {
        JButton btn = new JButton(text);
        btn.setFont(LABEL_FONT);
        btn.setFocusPainted(false);
        btn.setBackground(bgColor);
        btn.setForeground(Color.WHITE);
        btn.setBorder(BorderFactory.createEmptyBorder(8, 20, 8, 20));
        btn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 悬停效果
        btn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                btn.setBackground(bgColor.brighter());
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                btn.setBackground(bgColor);
            }
        });
        return btn;
    }

    private JButton createHelpButton() {
        JButton btn = new JButton("帮助");
        btn.setFont(LABEL_FONT);
        btn.setForeground(new Color(0, 150, 255));
        btn.setContentAreaFilled(false);
        btn.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5));
        btn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        btn.addActionListener(e -> showUserManual());
        return btn;
    }

    private void showUserManual() {
        JDialog manualDialog = new JDialog(this, "用户手册", true);
        manualDialog.setSize(500, 400);
        manualDialog.setLocationRelativeTo(this);

        JTextArea textArea = new JTextArea();
        textArea.setEditable(false);
        textArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setText(getManualContent());

        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        manualDialog.add(scrollPane);
        manualDialog.setVisible(true);
    }

    private String getManualContent() {
        return """
            ========== 坦克大战登录系统使用手册 ==========
            
            1. 用户登录
               - 用户名: 输入游戏账号(初始账号admin)
               - 密码: 输入对应的登录密码(初始密码123456)
               - 点击【登录】按钮进入游戏
            
            2. 按钮功能
               - 登录: 验证身份后进入游戏主界面
               - 取消: 退出登录系统
               - 帮助: 查看本使用手册
            
            3. 移动控制
               - 方向键 ↑：向上移动
               - 方向键 ↓：向下移动
               - 方向键 ←：向左移动
               - 方向键 →：向右移动
            
            4. 战斗控制q
               Ctrl键：发射普通子弹
               A键：发射超级子弹（同时向8个方向发射）
            
            技术支持: service@tankbattle.com
            版本号: v2.0.1
            """;
    }

    private class LoginHandler implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String user = usernameField.getText().trim();
            String pass = new String(passwordField.getPassword());

            if (validateLogin(user, pass)) {
                startGame();
            } else {
                JOptionPane.showMessageDialog(LoginFrame.this,
                        "用户名或密码错误！",
                        "登录失败",
                        JOptionPane.ERROR_MESSAGE);
            }
        }

        private boolean validateLogin(String user, String pass) {
            // 简单验证逻辑（实际项目应连接数据库）
            return "admin".equals(user) && "123456".equals(pass);
        }

        private void startGame() {
            dispose(); // 关闭登录窗口
            EventQueue.invokeLater(() -> {
                TankClient game = new TankClient();
                game.setTitle("坦克大战 - 当前用户: " + usernameField.getText());
                game.lauchFrame();
            });
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new LoginFrame().setVisible(true);
        });
    }
}